<?php

namespace app\admin\controller\coursetable;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-file
 */
class Coursetable extends Backend
{

    /**
     * Coursetable模型对象
     */
    protected $model = null;
    protected $noNeedRight = ["lists", "status", "tableDetail","recyclebin","restore","destroy"];
    protected $noNeedLogin = ["lists", "status", "tableDetail","recyclebin","restore","destroy"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Coursetable');
        $this->modelValidate = true;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");

            // 调试日志
            error_log("Coursetable Index - city_id: $city_id, school_id: $school_id");

            $total = $this->model
                ->where($where);

            // 添加城市过滤
            if (!empty($city_id)) {
                $total = $total->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤
            if (!empty($school_id)) {
                $total = $total->where("school_id", "=", $school_id);
            }

            $total = $total->where("status", "<>", -1)
                ->count();

            $list = $this->model
                ->where($where);

            // 添加城市过滤
            if (!empty($city_id)) {
                $list = $list->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }

            // 添加学校过滤
            if (!empty($school_id)) {
                $list = $list->where("school_id", "=", $school_id);
            }

            $list = $list->where("status", "<>", -1)
                ->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

            //            $tree = Tree::instance();
            //            $tree->init($list, 'pid');
            //            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
            //            $data = array();
            //            for ($i = 0; $i < count($list); $i++) {
            //                $v = $list[$i];
            //                $data[] = [
            //                    'id' => $v['id'],
            //                    'parent' => $v['pid'] ? $v['pid'] : '#',
            //                    'name' => $v['name'],
            //                    'type' => $v['type'],
            //                    'status' => $v['status'],
            //                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
            //                ];
            //            }


            for ($i = 0; $i < count($list); $i++) {
                //                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
                //                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
                //                $list[$i]['district_id']=model('Cityarea')->getDistrict_idTextAttr($list[$i]['district_id']);
                //                $list[$i]['province_id']=preg_replace("/\/$/","",model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id'])."/".$list[$i]['city_id']."/".$list[$i]['district_id']);
                $list[$i]['school_id'] = model('School')->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                //$v['ocation_id']=$this->model->getOcation_idTextAttr($v['ocation_id'],$v);
                $list[$i]['ocation_id'] = $this->model->getOcation_idTextAttr($list[$i]['ocation_id'], $list[$i]);
                //$v['classes_id']=$this->model->getClasses_idTextAttr($v['classes_id'],$v);
                $list[$i]['classes_id'] = $this->model->getClasses_idTextAttr($list[$i]['classes_id'], $list[$i]);
                //$v['teacher_id']=$this->model->getTeacher_idTextAttr($v['teacher_id'],$v);
                $list[$i]['teacher_id'] = $this->model->getTeacher_idTextAttr($list[$i]['teacher_id'], $list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        //        $this->assignconfig("relType",$_REQUEST['relType']);
        //        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    // 数据清理和验证
                    $this->cleanParams($params);

                    // 检查是否存在同名项目
                    if (isset($params['name']) && !empty($params['name'])) {
                        $existingProject = $this->model
                            ->where('name', $params['name'])
                            ->where('status', '<>', -1) // 排除已删除的记录
                            ->find();

                        if ($existingProject) {
                            $this->error('项目名称"' . $params['name'] . '"已存在，请更改项目名称');
                        }
                    }

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    // 自动插入session中的城市和学校ID
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }

                    // 调试日志
                    error_log("Coursetable Add - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                    $datatime = date("Y-m-d H:i:s");
                    $params['create_time'] = $datatime;
                    $params['update_time'] = $datatime;

                    // 移除不应该被设置的字段
                    unset($params['id']);
                    unset($params['delete_time']);

                    $params['start_date'] = (!array_key_exists("start_date", $params) || $params['start_date'] == "") ? date("Y-m-d", time()) : date("Y-m-d", strtotime($params['start_date']));
                    $params['ocation_id'] = is_array($params['ocation_id']) ? join(",", $params['ocation_id']) : $params['ocation_id'];
                    $params['classes_id'] = is_array($params['classes_id']) ? join(",", $params['classes_id']) : $params['classes_id'];

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error('数据库错误: ' . $e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("info", getUserInfo());
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }


        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    // 数据清理和验证
                    $this->cleanParams($params);

                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    // 自动插入session中的城市和学校ID（如果当前记录没有设置的话）
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        if (empty($row['city_id'])) {
                            $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                        }
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        if (empty($row['school_id'])) {
                            $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                        }
                    }

                    // 调试日志
                    error_log("Coursetable Edit - Auto inserted city_id: " . ($params['city_id'] ?? 'null') . ", school_id: " . ($params['school_id'] ?? 'null'));

                    $datatime = date("Y-m-d H:i:s");
                    $params['update_time'] = $datatime;

                    // 移除不应该被设置的字段
                    unset($params['id']);
                    unset($params['delete_time']);
                    unset($params['create_time']);

                    $params['ocation_id'] = is_array($params['ocation_id']) ? join(",", $params['ocation_id']) : $params['ocation_id'];
                    $params['classes_id'] = is_array($params['classes_id']) ? join(",", $params['classes_id']) : $params['classes_id'];

                    $params['start_date'] = (!array_key_exists("start_date", $params) || $params['start_date'] == "") ? date("Y-m-d", time()) : date("Y-m-d", strtotime($params['start_date']));
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        // 检查是否已有正式排课记录
                        $addmsg = "";
                        $formalCount = Db::name('course_table_autoplan')
                            ->where('table_id', $ids)
                            ->count();
                        if ($formalCount > 0) {
                            $addmsg = ",但需注意：由于该课程表已有正式排课记录！请先清除正式排课，需要进行重新排课。";
                            //$this->error('该课程表已有正式排课记录，不能修改！请先清除正式排课记录后再进行修改。');
                        }
                        $this->success("修改成功" . $addmsg);
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error('数据库错误: ' . $e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin", $_SESSION['think']['admin']);
        $row['ocation_id'] = $array = array_map('intval', explode(",", $row['ocation_id']));
        $row['classes_id'] = array_map('intval', explode(",", $row['classes_id']));
        preg_match_all("/([0-9\:\-]+)/", $row['holidays'], $matches);
        $arr = array();
        for ($i = 0; $i < count($matches[1]); $i++) {
            $arr[] = $matches[1][$i];
        }
        $row['holidays'] = join("\n", $arr);
        $this->view->assign("row", $row);
        $this->assignconfig("info", getUserInfo());
        return $this->view->fetch();
    }

    /**
     * 数据清理方法
     */
    private function cleanParams(&$params)
    {
        // 清理所有参数，移除空格和无效值
        foreach ($params as $key => $value) {
            if (is_string($value)) {
                $params[$key] = trim($value);
                // 如果值为 'NULL' 或空字符串，根据字段类型处理
                if ($params[$key] === 'NULL' || $params[$key] === '') {
                    if (in_array($key, ['id', 'school_id', 'teacher_id', 'weigh', 'status'])) {
                        // 对于整数字段，设置为 null 或默认值
                        if ($key === 'status') {
                            $params[$key] = 1; // 默认状态为正常
                        } elseif ($key === 'weigh') {
                            $params[$key] = 0; // 默认权重为0
                        } else {
                            unset($params[$key]); // 移除无效的ID字段
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "where status=1";
        if ($_SESSION['think']['admin']['group_id'] != 1) {
            $where .= " and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page = 1;
        $pagesize = 50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,\s*/", $keyValue);
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " and $keyField='{$nn[$i]}'";
                    }
                }
            } else {
                $where = "where status=1";
                if (isset($_REQUEST['city_id']) && $_REQUEST['city_id'] > 0) {
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql = "select id,name name from dev002_gxyusheng.fa_course_table $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);
        $total = db()->query("select count(1) as c from  dev002_gxyusheng.fa_course_table $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }


    public function tableDetail($ids = NULL)
    {
        // 查询招生简章表
        $enrollmentList = Db::name('course_table_autoplan_temp')
            ->alias('t')
            ->join('fa_course_table tb', 'tb.id=t.table_id', 'INNER')
            ->join('eb_school s', 'tb.school_id=s.id', 'INNER')
            ->join('eb_classes c', 'c.id=t.classes_id', 'INNER')
            ->join('fa_ocation o', 'o.id=t.ocation_id', 'INNER')
            ->join('fa_ocation o2', 'o.pid=o2.id', 'INNER')
            ->field("c.id,tb.name as project_name,tb.start_date,tb.end_date,s.name as school_name,c.num,c.intro,c.credit_exchange,c.description,c.num-apply_num as remaining_slots,o2.name as ocation_name,c.name as className,c.cover,subjectlv_id_b,c.price,tb.start_date")
            ->where("t.table_id", $_REQUEST['id'])
            ->group("t.ocation_id,t.classes_id")
            ->select();
        $data = array();
        $intro = "";
        $ocation_name = "";
        $subject = "";
        $num = 0;
        foreach ($enrollmentList as $key => $value) {
            if (empty($data)) {
                $data['project_name'] = preg_replace("/课程表/", "", $value['project_name']);
                $data['start_date'] = $value['start_date'];
                $data['end_date'] = $value['end_date'];
                $data['school_name'] = $value['school_name'];
                $data['cover'] = preg_replace('/^https?\:\/\/.*\.myqcloud\.com\//', 'https://tcimg.gxyushengwenhua.com/', $value['cover']);
            }
            $ocation_name .= $value['ocation_name'] . ",";
            $intro .= "<p><b>" . $value['subjectlv_id_b'] . "</b>:<br>" . $value['intro'] . "</p>";
            $num += intval($value['num']);
            $subject .= $value['subjectlv_id_b'] . ",";
        }
        $data['intro'] = $intro;
        $data['num'] = $num;
        $data['ocation_name'] = substr($ocation_name, 0, -1);
        $data['subject'] = substr($subject, 0, -1);
        echo json_encode(array("code" => 200, "data" => $data));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    /**
     * 检查是否有正式排课记录
     */
    public function checkFormalSchedule()
    {
        $table_id = $this->request->param('table_id', 0);

        if (!$table_id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        // 检查 fa_course_table_autoplan 表中是否存在该项目的记录
        $count = Db::name('course_table_autoplan')
            ->where('table_id', $table_id)
            ->count();

        return json([
            'code' => 1,
            'data' => ['has_formal' => $count > 0],
            'msg' => '查询成功'
        ]);
    }

    public function del($ids = null)
    {
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        // 检查是否有正式排课记录
        $count = Db::name('course_table_autoplan')
            ->where('table_id', $ids)
            ->count();
        if ($count > 0) {
            $this->error('该课程表已有正式排课记录，不能删除！请先清除正式排课记录后再进行删除。');
        }
        try {
            $this->model->where("id", "=", $ids)->delete();
            $this->success('删除成功!');
        } catch (Exception $e) {
            $this->error('删除失败!' . $e->getMessage());
        }
    }

    /**
     * 回收站列表
     */
    public function recyclebin()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch('recyclebin');
    }

    /**
     * 还原
     */
    public function restore($ids = null)
    {
        $row = $this->model->onlyTrashed()->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->restore();
        $this->success(__('Restore successful'));
    }

    /**
     * 彻底删除
     */
    public function destroy($ids = null)
    {
        $pk = $this->model->getPk();
        $this->model->destroy($ids);
        $this->success(__('Delete successful'));
    }
}
